package com.tencent.cloud.iov.router;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

/**
 * 页面路由器
 *
 * AndroidManifest 注册路由页面 action 格式为：${applicationId}.action.module.feature
 *
 * i.e. <action android:name="${applicationId}.action.car.control" />
 *
 * @author showxiao
 * @date 2018/5/22
 */

public class Router {

    private static final String ACTION_INFIX = ".action";

    @SuppressLint("StaticFieldLeak")
    private static Context sContext;

    public static void init(Context context) {
        sContext = context.getApplicationContext();
    }

    /**
     * 通过页面路径创建隐式 Intent
     *
     * @param path      页面路径 (i.e. /car/control)
     * @return          Intent  (i.e. action: com.package.name.action.car.control)
     */
    public static Intent fromPath(String path) {
        if (sContext == null) {
            throw new IllegalStateException("Router should be init first");
        }

        if (path == null || path.isEmpty()) {
            throw new IllegalArgumentException("path should not be empty");
        }

        String actionSuffix = path.replaceAll("/", ".");

        String action = sContext.getPackageName() + ACTION_INFIX + actionSuffix;
        Intent intent = new Intent(action);

        if (intent.resolveActivity(sContext.getPackageManager()) == null) {
            throw new IllegalArgumentException("action [" + action + "] for path [" + path + "] " +
                    "has not been registered");
        }

        return intent;
    }

}
